<?php

if(!defined('_COMMON_')) {
define('_COMMON_', 1);

include  _FLEP_LIB_DIR_.'search.inc.php';

/**
 * Starts the php session.<br>
 * A new one is created if the previous one already expired.
 */
function flep_session_start() {
  session_set_cookie_params( _FLEP_SESSION_TIMEOUT_, _FLEP_SERVER_DIR_);
  session_name('fleps');
  session_start();
  setcookie(session_name(), session_id(), time() +  _FLEP_SESSION_TIMEOUT_);
}

/**
 * Ends the session.
 */
function flep_logout() {
  session_unset();
  session_destroy();
}

/**
 * Starts the session.
 * 
 * @return boolean <b>true</b> on success.
 * <b>false</b> on failure.
 */
function flep_login(&$auth_data) {
  $auth_data['msg'] =  _FLEP_INCORRECT_PASS_MSG_;
  $user_pass = $auth_data['data'][0]['clave'];
  $auth_data['where'] = array('usuario="'.$auth_data['data'][0]['usuario'].'"');
  if (flep_search_all($auth_data)) {
    if ($auth_data['data'][0]['clave'] === $user_pass) {
      $auth_data['msg'] = null; //TODO: Implement Browser and IP verification to avoid false authentication.
      return $auth_data['login'] = true;
    }
  }
  return $auth_data['login'] = false;
}

/**
 * Valid session.
 * 
 * @return boolean <b>true</b> on success.
 * <b>false</b> on failure.
 */
function flep_valid_login(&$auth_data) {
  if (isset($auth_data['login']) && $auth_data['login']) {
    return $auth_data['login'] = flep_login($auth_data);
  }
  return false;
}

function flep_structure(&$data, $type) {
  if (file_exists( _FLEP_STRUCT_DIR_ . '/' . $type . '.inc.php')) {
    include  _FLEP_STRUCT_DIR_ . '/' . $type . '.inc.php';
    return true;
  }
  return false;
}

function flep_get(&$data, $field, $i = 0) {
  if (array_key_exists('data', $data) && array_key_exists($field, $data['data'][$i])) {
    return $data['data'][$i][$field];
  }
  return null;
}

function flep_array_value(&$array, $idx){
  return isset($array[$idx])? $array[$idx] : null;
}

function flep_encode($id) {
  $rnd = openssl_random_pseudo_bytes(8);
  return base_convert($id . bin2hex($rnd), 16, 10);
}

function flep_decode($id) {
  if (!is_numeric($id))
    return 0;
  $str = sprintf("%032s", base_convert($id, 10, 16));
  return sprintf("%d", substr($str, 0, 16));
}

function flep_pass($pass) {
  return md5($pass);
}

}
?>
